BUILD_DIR=./build
IMG_NAME=fuquOS.img

BIN_FILE := $(BUILD_DIR)/fuqu.bin
IMG_FILE := $(BUILD_DIR)/$(IMG_NAME)
BIN_SIZE := $(shell stat -f%z $(BIN_FILE))
BIN_SECTORS := $(shell echo $$(( ($(BIN_SIZE)+511)/512 )) )
IMG_SIZE := $(shell stat -f%z $(IMG_FILE))
IMG_SECTORS := $(shell echo $$(( ($(IMG_SIZE))/512 )) )
PART2_START := $(shell echo $$((2 + $(BIN_SECTORS))) )
PART2_SIZE := $(shell echo $$(( $(IMG_SECTORS) - $(PART2_START) )) )

CC = x86_64-elf-gcc
LD = x86_64-elf-ld
OBJCOPY = x86_64-elf-objcopy

CFLAGS:= -m32
CFLAGS+= -fno-builtin#不需要内置函数
CFLAGS+= -nostdinc#不需要标准头文件
CFLAGS+= -fno-pic#不需要位置无关的代码
CFLAGS+= -fno-pie#不需要位置无关的可执行文件
CFLAGS+= -nostdlib#不需要标准库
CFLAGS+= -fno-stack-protector#不需要栈保护
CFLAGS:=$(strip ${CFLAGS})

DEBUG:= -g
INCLUDE:=-I./include -I./test

run: build_boot build_kernel
	qemu-system-i386 -name "FuQu" -m 4G -drive file=$(BUILD_DIR)/$(IMG_NAME) -boot d -smp cores=4,threads=2

debug: build_boot build_kernel
	qemu-system-i386 -name "FuQu" -m 1G -drive file=$(BUILD_DIR)/$(IMG_NAME) -boot d -S -s -rtc base=localtime -smp cores=4,threads=2
clean:
	rm -rf $(BUILD_DIR)

$(BUILD_DIR)/%.o: ./%.c
	mkdir -p $(dir $@)
	$(CC) $(CFLAGS) $(DEBUG) $(INCLUDE) -c $< -o $@

$(BUILD_DIR)/%.o: ./%.asm
	mkdir -p $(dir $@)
	nasm -f elf32 -o $@ $<

build_boot: clean create_img
	mkdir -p $(BUILD_DIR)/boot
	nasm -f bin -o $(BUILD_DIR)/boot/boot.bin boot/boot.asm
	nasm -f bin -o $(BUILD_DIR)/boot/setup.bin boot/setup.asm


build_kernel: $(BUILD_DIR)/kernel/main.o \
				$(BUILD_DIR)/kernel/io.o \
				$(BUILD_DIR)/kernel/printk.o \
				$(BUILD_DIR)/kernel/number.o \
				$(BUILD_DIR)/kernel/loader.o \
				$(BUILD_DIR)/kernel/idt.o \
				$(BUILD_DIR)/kernel/idt_table.o \
				$(BUILD_DIR)/kernel/memory.o \
				$(BUILD_DIR)/kernel/gdt.o \
				$(BUILD_DIR)/kernel/string.o \
				$(BUILD_DIR)/kernel/stdio.o \
				$(BUILD_DIR)/kernel/pit.o \
				$(BUILD_DIR)/kernel/timer.o \
				$(BUILD_DIR)/kernel/tools.o \
				$(BUILD_DIR)/kernel/cpu.o \
				$(BUILD_DIR)/kernel/block.o \
				$(BUILD_DIR)/kernel/fat32.o \
				$(BUILD_DIR)/test/kernel_isr/kernel_idt_test.o
	$(LD) -m elf_i386 -static -Ttext 0x10000 -o $(BUILD_DIR)/fuqu.elf $^
	$(OBJCOPY) -O binary $(BUILD_DIR)/fuqu.elf $(BUILD_DIR)/fuqu.bin
	nm $(BUILD_DIR)/fuqu.elf|sort > $(BUILD_DIR)/fuqu.map
	mbr_tool $(BUILD_DIR)/$(IMG_NAME) 0 $(BIN_SECTORS) $(PART2_START) $(PART2_SIZE)
	dd if=$(BUILD_DIR)/boot/boot.bin of=$(BUILD_DIR)/$(IMG_NAME) bs=446 count=1 conv=notrunc
	dd if=$(BUILD_DIR)/boot/setup.bin of=$(BUILD_DIR)/$(IMG_NAME) bs=512 count=1 seek=1 conv=notrunc
	dd if=$(BIN_FILE) of=$(IMG_FILE) bs=512 count=$(BIN_SECTORS) seek=2 conv=notrunc
	fat32_format $(BUILD_DIR)/$(IMG_NAME) $(PART2_START) $(PART2_SIZE) 8

create_img:
	mkdir $(BUILD_DIR)
	dd if=/dev/zero of=$(BUILD_DIR)/$(IMG_NAME) bs=1M count=512
